using System;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace DatabaseTest
{
    class Program
    {
        private static string _connectionString = "Server=113.45.182.203;Database=weapons;Uid=webuser;Pwd=Mttqwe101!;CharSet=utf8mb4;SslMode=0;ConnectionTimeout=30;";
        
        static async Task Main(string[] args)
        {
            Console.WriteLine("开始测试数据库连接...");
            
            try
            {
                using (var connection = new MySqlConnection(_connectionString))
                {
                    Console.WriteLine($"尝试连接数据库: {_connectionString}");
                    await connection.OpenAsync();
                    Console.WriteLine("数据库连接成功");
                    
                    string query = "SELECT COUNT(*) FROM schemes WHERE status = 'normal'";
                    Console.WriteLine($"执行查询: {query}");
                    
                    using (var command = new MySqlCommand(query, connection))
                    {
                        var count = await command.ExecuteScalarAsync();
                        Console.WriteLine($"数据库中共有 {count} 条正常状态的方案记录");
                    }
                    
                    // 尝试获取前5条记录
                    query = "SELECT id, category, weapon_name, description, price, uses, scheme_content FROM schemes WHERE status = 'normal' ORDER BY uses DESC LIMIT 5";
                    Console.WriteLine($"执行查询: {query}");
                    
                    using (var command = new MySqlCommand(query, connection))
                    {
                        using (var reader = await command.ExecuteReaderAsync())
                        {
                            int recordCount = 0;
                            while (await reader.ReadAsync())
                            {
                                recordCount++;
                                Console.WriteLine($"记录 {recordCount}: ID={reader.GetInt32(0)}, Category={(reader.IsDBNull(1) ? "NULL" : reader.GetString(1))}, Weapon={(reader.IsDBNull(2) ? "NULL" : reader.GetString(2))}");
                            }
                            Console.WriteLine($"成功读取 {recordCount} 条记录");
                        }
                    }
                }
                
                Console.WriteLine("数据库测试完成，按任意键退出...");
                Console.ReadKey();
            }
            catch (MySqlException ex)
            {
                Console.WriteLine($"MySQL错误 {ex.Number}: {ex.Message}");
                Console.WriteLine($"错误堆栈: {ex.StackTrace}");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取方案数据时出错: {ex.Message}");
                Console.WriteLine($"错误堆栈: {ex.StackTrace}");
                Console.WriteLine("按任意键退出...");
                Console.ReadKey();
            }
        }
    }
}
